package dao

import (
	"fmt"
	"lib/structs/tables"
	"vap/global"
)

var HostRepository = new(hostRepository)

type hostRepository struct{}

// FindHostByHostUId 根据主机uid查询主机信息
func (r hostRepository) FindHostByHostUId(uid string) (m tables.VapHost, err error) {
	err = global.DB.Model(&tables.VapHost{}).Where("uid = ?", uid).Find(&m).Error
	return
}

func (r hostRepository) FindInstallAppList(clusterId int64) (li []tables.VapAppInstall, err error) {
	err = global.DB.Model(&tables.VapAppInstall{}).Where("host_id in (select id from vap_host where cluster_id = ? )", clusterId).Find(&li).Error
	return
}

func (r hostRepository) FindHostAll() (li []tables.VapHost, total int64, err error) {
	err = global.DB.Model(&tables.VapHost{}).
		Find(&li).Count(&total).Error
	return
}

func (r hostRepository) FindHostById(id int64) (m tables.VapHost, err error) {
	err = global.DB.Model(&tables.VapHost{}).Where(&tables.VapHost{Id: id}).First(&m).Error
	return
}

func (r hostRepository) UpdateHostById(m *tables.VapHost) (err error) {
	if _, err = r.FindHostById(m.Id); err != nil {
		return fmt.Errorf("host not exist")
	}
	return global.DB.Save(m).Error
}

func (r hostRepository) CreateHost(m *tables.VapHost) (err error) {
	return global.DB.Create(m).Error
}

func (r hostRepository) FindPrivateHost(userId, clusterId int64) (m tables.VapHost, err error) {
	err = global.DB.Model(&tables.VapHost{}).Where("bind_user_id = ? and cluster_id = ? ", userId, clusterId).Find(&m).Error
	if err != nil {
		return
	}
	return
}

// SelectZeroSessionHost 查询活跃会话数为0且没有被私人绑定也没有被锁定的主机，也就是完全空闲的主机
func (r hostRepository) SelectZeroSessionHost(clusterId int64) (li []tables.VapHost, err error) {
	err = global.DB.Raw("SELECT * FROM vap_host WHERE "+
		" cluster_id =? AND bind_user_id =0 AND locked_user_id =0 "+
		" AND id NOT IN "+
		" ( SELECT host_id FROM 'vap_session' WHERE cluster_id =1 AND hold_status = ? )",
		clusterId, tables.VaSessionHoldForHolding).Find(&li).Error
	return
}

func (r hostRepository) FindWithClusterId(clusterId int64) (li []tables.VapHost, err error) {
	err = global.DB.Where("cluster_id = ? ", clusterId).Find(&li).Error
	return
}

func (r hostRepository) FindClusterById(clusterId int64) (clu tables.VapCluster, err error) {
	err = global.DB.Where("id =?", clusterId).Find(&clu).Error
	return
}

func (r hostRepository) FindByHostUid(uid string) (m tables.VapHost, err error) {
	err = global.DB.Where("uid = ? ", uid).Limit(1).Find(&m).Error
	return
}
